'''
https://leetcode.cn/problems/number-of-closed-islands/?envType=study-plan-v2&envId=graph-theory
'''
from typing import List

class Solution:

    def closedIsland(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])

        def dfs(x, y):
            if x == 0 or y == 0 or x == m - 1 or y == n - 1:
                return True
            grid[x][y] = 2
            res = False
            for tx, ty in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
                if grid[tx][ty] == 0 and dfs(tx, ty):
                    res = True
            return res

        res = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 0 and not dfs(i, j):
                    res += 1
        return res


grid = [[0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0],
        [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0]]
print(Solution().closedIsland(grid))
